//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj修改手机号码

#import "ChangPhoneNumberVC.h"
#import "LanguageController.h"
#import "CountryCodeVC.h"
#import "RegisterViewController.h"
#import "AllCountryCodeVC.h"
#import "NBPhoneNumberUtil.h"
#import "CaptchaView.h"
#import "EnterCodeController.h"
#import "MJConfirmLoadingView.h"

@interface ChangPhoneNumberVC ()
@property (weak, nonatomic) IBOutlet UILabel *countryCodeLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentPhoneLabel;

@property (weak, nonatomic) IBOutlet MJUITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet MJConfirmLoadingView *confirmButton;
@property (weak, nonatomic) IBOutlet UIView *phoneNumberBgView;
@property (nonatomic, strong) NSDictionary *countryAreaCode;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@end

@implementation ChangPhoneNumberVC

- (void)viewDidLoad {
    [super viewDidLoad];
 
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)mj_setUI{
    [super mj_setUI];
    
    self.phoneNumberTextField.mj_disableThirdPartyKeyboard = true;
//    self.phoneNumberTextField.font = MJUIFontBoldMake(26);
    
    self.tipLabel.hidden = true;
    self.countryCodeLabel.text = @"";
    [self.phoneNumberTextField mj_setClearButtonWithImage:[UIImage imageNamed:@"icon_del"]];
    [self.phoneNumberTextField mj_becomeFirstResponder];
    
    if(UserManager.shared.userModel.countryCode){
        NSDictionary *countryAreaCode = [HealthHelper getCountryWithCountryCode:UserManager.shared.userModel.countryCode];
        self.countryAreaCode = countryAreaCode;
    }else{
        self.countryAreaCode = [HealthHelper getCountryAreaCode];
    }
    
    
    NSString *code = [NSString stringWithFormat:@"+%@",self.countryAreaCode[@"区号"]];
    self.countryCodeLabel.text = code;
    
    NSString *phoneNumber = UserManager.shared.userModel.phoneNumber;
    if(phoneNumber){
        NSString *currentPhone = [NSString stringWithFormat:@"%@-%@",self.countryAreaCode[@"区号"],UserManager.shared.userModel.phoneNumber];
        self.currentPhoneLabel.text = [NSString stringWithFormat:@"%@ %@\n%@",MJUILocalizedString(@"The current phone number is"),currentPhone,MJUILocalizedString(@"You can login with the new number after changing")];
        if([self.countryCodeLabel.text containsString:@"+86"]){
            self.phoneNumberTextField.mj_limitedNumber = 11;
        }
    }else{
        self.currentPhoneLabel.text = MJUILocalizedString(@"You can login with the new number after linking");
        self.titleLabel.text = MJUILocalizedString(@"Link Phone Number");
    }
    
    
    
    NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
    MJWeakSelf
    RAC(self.confirmButton, enabled) = [RACSignal combineLatest:@[self.phoneNumberTextField.rac_textSignal] reduce:^id _Nullable(NSString * text){
        
        BOOL enable = false;
        if([self.countryCodeLabel.text containsString:@"+86"]){
            if(text.length == 11 && [text mj_isMobileNumber]){
                enable = true;
            }else{
                enable = false;
            }
        }else{
            NBPhoneNumber *myNumber = [phoneUtil parse:text
                                          defaultRegion:weakSelf.countryAreaCode[@"ISO"] error:nil];
            enable = [phoneUtil isValidNumber:myNumber];
            NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber] ? @"YES":@"NO");
        }
      
        if(enable){
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_appColor width:2];
        }else{
            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.clearColor width:2];
            weakSelf.tipLabel.hidden = true;
        }
        return @(enable);
    }];
    self.confirmButton.handleContinueBlock = ^{
        [weakSelf handleConfirmButtonClick];

    };

}

#pragma mark - 方法
- (void)requestData{
    
}

- (IBAction)handleCountryCodeButtonClick:(UIButton *)sender {
    MJWeakSelf
    AllCountryCodeVC *vc = [[AllCountryCodeVC alloc]init];
    vc.handleCountryCodeBlock = ^(NSDictionary *countryAreaCode) {
        NSString *code = [NSString stringWithFormat:@"+%@",countryAreaCode[@"区号"]];
        weakSelf.countryCodeLabel.text = code;
        weakSelf.countryAreaCode = countryAreaCode;

    };
    [self.navigationController pushViewController:vc animated:true];
}

- (void)handleConfirmButtonClick{
    [self.phoneNumberTextField resignFirstResponder];
    
    [self.confirmButton.loadingView startAnimation];

    NSDictionary *params =  @{
        @"countryCode": self.countryAreaCode[@"区号"],
        @"phoneNumber": self.phoneNumberTextField.text,
        @"region": self.countryAreaCode[@"ISO"],
    };
    MJWeakSelf
    [MJHttpNetWorking requestWithParams:params requestUri:user_findByPhone requestType:RequestTypeGet showLoading:false success:^(MJBaseModel *model) {
        [weakSelf.confirmButton.loadingView stopAnimation];

        if(model.code == 200){
            if(model.data){
                [RoyHud showToast:MJUILocalizedString(@"Phone number already in use")];
            }else{
                [CaptchaView showWithType: puzzle CompleteBlock:^(NSString *  result) {
                    NSLog(@"result=======================%@",result);
                    NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{
                        @"countryCode": self.countryAreaCode[@"区号"],
                        @"phoneNumber": self.phoneNumberTextField.text,
                        @"region": self.countryAreaCode[@"ISO"],
                        @"code": result,
                    }];
                    [weakSelf.confirmButton.loadingView startAnimation];

                    [MJHttpNetWorking requestWithParams:parms requestUri:captcha_sendSms requestType:RequestTypePost showLoading:false success:^(MJBaseModel *model) {
                        [weakSelf.confirmButton.loadingView stopAnimation];

                        if (model.code ==  200){
                            
                            EnterCodeController *vc = [[EnterCodeController alloc]init];
                            vc.captchaCodeType = CaptchaCodeTypeChangePhone;
                            vc.phone = weakSelf.phoneNumberTextField.text;
                            vc.countryAreaCode = weakSelf.countryAreaCode;
                            [weakSelf.navigationController pushViewController:vc animated:true];
                        }else if(model.code ==  412){
                            [RoyHud showToast:MJUILocalizedString(@"Too frequent, Retry later.")];
                        }
                        
                    } failure:^(NSError *error) {
                        [weakSelf.confirmButton.loadingView stopAnimation];

                    }];
                }];
            }
        }

    } failure:^(NSError *error) {
        [weakSelf.confirmButton.loadingView stopAnimation];

    }];
    
    
    
//    MJWeakSelf
//    [MJHttpNetWorking requestWithParams:@{@"appName":@"uricacid",@"deviceType":@"iOS"} requestUri:GetAppUpgrade requestType:RequestTypeGet showLoading:true success:^(MJBaseModel *model) {
//        
//        if(model.code == 200){
//            weakSelf.tipLabel.hidden = false;
//            [weakSelf.phoneNumberBgView mj_borderColor:UIColor.mj_redColor width:2];
//        }
//
//    } failure:^(NSError *error) {
//        
//    }];
}


#pragma mark - 代理

#pragma mark - 懒加载

@end
